<template>
  <div class="min-h-screen bg-gray-50">
    <div class="container mx-auto px-4 py-8">
      <!-- 页面头部 -->
      <div class="flex justify-between items-center mb-8">
        <div>
          <h1 class="text-3xl font-bold text-gray-800 mb-2">题库管理</h1>
          <p class="text-gray-600">管理你的自定义题库，让游戏更有趣</p>
        </div>
        <div class="flex gap-3">
          <button
            @click="$router.push('/')"
            class="px-4 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600 transition-colors"
          >
            返回首页
          </button>
          <button
            @click="showCreateModal = true"
            class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
          >
            创建题库
          </button>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="text-center py-12">
        <div
          class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"
        ></div>
        <p class="mt-2 text-gray-600">加载中...</p>
      </div>

      <!-- 错误状态 -->
      <div v-else-if="error" class="text-center py-12">
        <div class="text-red-500 mb-4">
          <svg
            class="w-16 h-16 mx-auto mb-4"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
            ></path>
          </svg>
          <p class="text-lg font-medium">{{ error }}</p>
        </div>
        <button
          @click="loadWordBanks"
          class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
        >
          重试
        </button>
      </div>

      <!-- 题库列表 -->
      <div v-else class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <div
          v-for="wordBank in wordBanks"
          :key="wordBank.id"
          class="bg-white rounded-lg shadow-md border border-gray-200 p-6 hover:shadow-lg transition-shadow"
        >
          <div class="flex justify-between items-start mb-4">
            <div>
              <h3 class="text-lg font-semibold text-gray-800 mb-1">
                {{ wordBank.name }}
              </h3>
              <p class="text-sm text-gray-600">
                {{ wordBank.wordCount }} 个词汇
              </p>
            </div>
            <div class="flex items-center gap-2">
              <span
                v-if="wordBank.isDefault"
                class="px-2 py-1 bg-green-100 text-green-800 text-xs rounded-full"
              >
                默认
              </span>
              <span
                v-else
                class="px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded-full"
              >
                自定义
              </span>
            </div>
          </div>

          <div class="text-xs text-gray-500 mb-4">
            创建时间: {{ formatDate(wordBank.createdAt) }}
          </div>

          <div class="flex gap-2">
            <button
              @click="viewWordBank(wordBank.id)"
              class="px-3 py-2 bg-gray-100 text-gray-700 rounded hover:bg-gray-200 transition-colors text-sm"
            >
              查看
            </button>
            <button
              v-if="!wordBank.isDefault"
              @click="editWordBank(wordBank.id)"
              class="px-3 py-2 bg-blue-100 text-blue-700 rounded hover:bg-blue-200 transition-colors text-sm"
            >
              编辑
            </button>
            <button
              v-if="!wordBank.isDefault"
              @click="confirmDelete(wordBank.id)"
              class="px-3 py-2 bg-red-100 text-red-700 rounded hover:bg-red-200 transition-colors text-sm"
            >
              删除
            </button>
            <button
              @click="toggleWordBankSelection(wordBank.id)"
              class="px-3 py-2"
              :class="[
                selectedWordBankId === wordBank.id
                  ? 'bg-green-500 text-white'
                  : 'bg-gray-100 text-gray-700',
                'rounded hover:opacity-90 transition-colors text-sm',
              ]"
            >
              {{ selectedWordBankId === wordBank.id ? "已选择" : "选择" }}
            </button>
          </div>
        </div>

        <!-- 空状态 -->
        <div
          v-if="wordBanks.length === 0"
          class="col-span-full text-center py-12"
        >
          <svg
            class="w-16 h-16 mx-auto mb-4 text-gray-400"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
            ></path>
          </svg>
          <p class="text-gray-600 mb-4">还没有题库</p>
          <button
            @click="showCreateModal = true"
            class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
          >
            创建第一个题库
          </button>
        </div>
      </div>
    </div>

    <!-- 创建题库模态框 -->
    <CreateWordBankModal
      v-if="showCreateModal"
      @close="showCreateModal = false"
      @created="handleWordBankCreated"
    />

    <!-- 查看题库模态框 -->
    <ViewWordBankModal
      v-if="showViewModal && selectedWordBank"
      :word-bank="selectedWordBank"
      @close="showViewModal = false"
    />

    <!-- 编辑题库模态框 -->
    <EditWordBankModal
      v-if="showEditModal && selectedWordBank"
      :word-bank="selectedWordBank"
      @close="showEditModal = false"
      @updated="handleWordBankUpdated"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import {
  apiService,
  type WordBank,
  type WordBankDetail,
} from "../services/api";
import { useGameConfigStore } from "../stores/gameConfig";
import CreateWordBankModal from "../components/CreateWordBankModal.vue";
import ViewWordBankModal from "../components/ViewWordBankModal.vue";
import EditWordBankModal from "../components/EditWordBankModal.vue";

const gameConfigStore = useGameConfigStore();

const wordBanks = ref<WordBank[]>([]);
const loading = ref(false);
const error = ref("");
const showDeleteConfirm = ref(false);
const wordBankToDelete = ref("");

const showCreateModal = ref(false);
const showViewModal = ref(false);
const showEditModal = ref(false);
const selectedWordBank = ref<WordBankDetail | null>(null);

const selectedWordBankId = computed(() => gameConfigStore.selectedWordBankId);

// 加载题库列表
const loadWordBanks = async () => {
  loading.value = true;
  error.value = "";

  try {
    wordBanks.value = await apiService.getWordBanks();
  } catch (err) {
    error.value = err instanceof Error ? err.message : "加载失败";
  } finally {
    loading.value = false;
  }
};

// 查看题库详情
const viewWordBank = async (id: string) => {
  try {
    selectedWordBank.value = await apiService.getWordBank(id);
    showViewModal.value = true;
  } catch (err) {
    console.error("查看题库失败:", err);
  }
};

// 编辑题库
const editWordBank = async (id: string) => {
  try {
    selectedWordBank.value = await apiService.getWordBank(id);
    showEditModal.value = true;
  } catch (err) {
    console.error("获取题库详情失败:", err);
  }
};

// 处理题库创建成功
const handleWordBankCreated = () => {
  showCreateModal.value = false;
  loadWordBanks();
};

// 处理题库更新成功
const handleWordBankUpdated = () => {
  showEditModal.value = false;
  loadWordBanks();
};

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString("zh-CN");
};

// 删除确认
const confirmDelete = (id: string) => {
  if (confirm("确定要删除这个词库吗？")) {
    deleteWordBank(id);
  }
};

// 删除题库
const deleteWordBank = async (id: string) => {
  try {
    await apiService.deleteWordBank(id);
    gameConfigStore.deleteWordBank(id);
    loadWordBanks();
  } catch (err) {
    console.error("删除词库失败:", err);
  }
};

// 切换词库选择
const toggleWordBankSelection = (id: string) => {
  if (selectedWordBankId.value === id) {
    gameConfigStore.setSelectedWordBank("");
  } else {
    gameConfigStore.setSelectedWordBank(id);
  }
};

onMounted(() => {
  loadWordBanks();
});
</script>
